let that,innerAudioContext,
api = new(require('../../utils/api.js')),
headimg = api.getimgurl(),
headaudio = api.getaudiourl(),
audiohead='https://www.jihemu.com/bookapi/myaudio/',
app = getApp(),
util = new(require('../../utils/util.js'));
Page({

  /**
   * 页面的初始数据
   */
  data: {
    audiohead,
    showid:0,
    rdata:[],
    headimg,
    headaudio,
    formatCurrentTime: '00:00',
    formatDuration: '00:00',
    luyin:'',
    issaying:!1,
    isplay:!1,
    duration:0,
    currentTime:0,
    useranswer:'',
    islast:!1,
    worksid:0,//作品集id
    islike:'0',//是否点赞 0 否 1 是
    sampledata:'',
    isshow:!0,
    currentindex:0,
    sendshow:!1,
    newcomment:'',
    pagesize: 20,
    start: 0,
    flag: !0,
    nickName: '',
    avatarUrl: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
    let  {id} = options,{currentindex,list}=that.data

    that.setData({id},()=>{
      if (app.logininfo) {
        console.log('herere');
          that.getdata()
      } else {
        util.setwatcher(app, that.afterlogin)
      }
    })
  
},
afterlogin: {
  logininfo: res => {
    that.getdata();
  }
},
getdata(){
  wx.showLoading({
    title: '加载中',
  })
  let {id}=that.data
  api.share_getd(id,res=>{
    wx.hideLoading()
    if(res.data.issuccess==1){
       let {data}=res.data,rdata = JSON.parse(util.decodeurl(data.rawData)),total=0
       rdata.forEach(x=>{
         total+=x.amount
       })
       that.setData({data,rdata,total})
       console.log(rdata,'rdatardata');

      // list.forEach(x=>{
      //   x['audiosrc']=audiohead+x.useranswer
      //   x['date'] = util.formatTime(new Date(x.changeDate*1000))
      //   x['thumbpath'] = headimg+x.imgsrc
      //   x['contents']=x.contents.replace(/&#39;/g,'\'');
      //   imglist.push(x.thumbpath)
      // })
      // sampledata=res.data.list[0]

      // that.setData({islike,list,sampledata,imglist})
    }else{
      wx.showModal({
        title: '提示',
        content: res.data.msg,
        showCancel:!1,
        complete: (res) => {
          if (res.confirm) {
              wx.navigateBack()
          }
        }
      })
    }
  })
 // that.getdata(worksid)
  // that.getcommlist()
},
  //播放
 play(){
  let {sampledata} = that.data
  that.setData({isshow:!1},()=>{
    that.changenewaudio(sampledata)
  })
 },
 nextplay(){
  let {sampledata,list,currentindex} = that.data
  sampledata=list[currentindex]
  that.setData({sampledata},()=>{
      setTimeout(function () {
        that.changenewaudio(sampledata)
      },1000)
    })
 },
  changenewaudio(audio){
    console.log('changenewaudio', audio)
    innerAudioContext.stop();
    innerAudioContext.src=audio.audiosrc;
    innerAudioContext.title=audio.contents||'a';
    innerAudioContext.play();
    that.setData({
      isplay: !0,
      // duration, formatDuration
    })
    innerAudioContext.onCanplay(()=>{
      that.initaudio(innerAudioContext.duration)
      
    })

  },
  initaudio(duration){
    console.log('initaudio')
    let formatDuration = '';
    wx.hideLoading();
     // innerAudioContext.duration
      duration = innerAudioContext.duration
      duration = Math.ceil(duration)
      formatDuration = that.formatSeconds(duration)
      that.setData({
        // isplay: !0,
        duration, formatDuration
      })

      innerAudioContext.onTimeUpdate(()=>{
        let currentTime = Math.ceil(innerAudioContext.currentTime);
        that.setData({
          duration:innerAudioContext.duration,
          formatDuration:that.formatSeconds(innerAudioContext.duration),
          currentTime ,
          formatCurrentTime: that.formatSeconds(currentTime),
        })
      })
    //监听音乐暂停
    innerAudioContext.onPause(res => {
      that.setData({
        isplay: !1
      })
    })
  },
  /**
   * 进度条事件
   */
  sliderChange(e) {
    let percent = e.detail.value,
      {
        duration
      } = that.data;
    if (innerAudioContext.paused) {
      innerAudioContext.seek(percent)
    } else {
      innerAudioContext.seek(percent)
    }
  },
    /**
   *  时间格式化
   */
  formatSeconds(value) {
    if(isNaN(value)) return "00:00";
    var secondTime = parseInt(value); // 秒
    var minuteTime = 0; // 分
    var hourTime = 0; // 小时
    if (secondTime >= 60) { //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
     
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime >= 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60);
       
      }
    }
    minuteTime = minuteTime + hourTime * 60;
    if (secondTime < 10) {
      secondTime = "0" + secondTime
    }
    if (minuteTime < 10) {
      minuteTime = "0" + minuteTime
    }
    var result = minuteTime + ':' + secondTime;
    
    return result;
  },
  preheadImg:function(e){
    var src = e.currentTarget.dataset.src;
    let headimg=[]
    headimg.push(src)
    // var imglist = this.data.imglist;
    wx.previewImage({
      current:src,     //当前图片地址
      urls: headimg,               //所有要预览的图片的地址集合 数组形式
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  switchSubject(e){
    let {index,type} = e.currentTarget.dataset,{list,subjectdata,PronFluency,PronCompletion,SuggestedScore,useranswer}=that.data
    if(type=='next'){
      if(index==list.length-1){
        if(useranswer==''){
          wx.showModal({
            title: '提示',
            content:subjectdata.type=='FOLLOWUP'?'请先跟读':'请先答题',
            showCancel:!1
          })
          return
        }else{
          that.setData({islast:!0},()=>{
            that.aoeEvaluating()
          })
        }
      }else{
        index=index+1
        subjectdata=list[index]
        let id = subjectdata.id
        if(useranswer==''){
          wx.showModal({
            title: '提示',
            content:subjectdata.type=='FOLLOWUP'?'请先跟读':'请先答题',
            showCancel:!1
          })
          return
        }else{
          that.aoeEvaluating()
          api.getEvaluatingDetail(id,res=>{
            if(res.data.issuccess==1){
              if(res.data.data){
                let {data} = res.data
                that.setData({isshow:!0,useranswer:data.useranswer,PronFluency:data.fluency,PronCompletion:data.integrity,SuggestedScore:data.totalscore})
              }
              console.log(res.data.data,'getEvaluatingDetailgetEvaluatingDetail');
            }
          })
          if(subjectdata.audiosrc.indexOf('http')==-1){
            subjectdata.audiosrc=headaudio+subjectdata.audiosrc
          }
          that.changenewaudio(subjectdata)
        }
      }
    }else{
      if(index==0){
        wx.showToast({
          title: '已经是第一题了',
          icon:'none'
        })
        return
      }else{
        index=index-1
        subjectdata=list[index]
        let id = subjectdata.id
        if(subjectdata.audiosrc.indexOf('http')==-1){
          subjectdata.audiosrc=headaudio+subjectdata.audiosrc
        }
        that.changenewaudio(subjectdata)
        api.getEvaluatingDetail(id,res=>{
          if(res.data.issuccess==1){
            if(res.data.data){
              let {data} = res.data
              that.setData({isshow:!0,useranswer:data.useranswer,PronFluency:data.fluency,PronCompletion:data.integrity,SuggestedScore:data.totalscore})
            }
            console.log(res.data.data,'getEvaluatingDetailgetEvaluatingDetail');
          }
        })
      }
    }
    that.setData({subjectdata,index})
  },
  choice(e){
    let {value} = e.currentTarget.dataset,{useranswer}=that.data
    if(useranswer==value) return
    that.setData({useranswer:value})
  },

  thumbsup(e){
    let {islike,worksid,commentsdata}=that.data
    if(islike==0){
      api.dofavor(worksid,res=>{
        if(res.data.issuccess==1){
          wx.showToast({
            title: '点赞成功',
            icon:'none',
            duration:1000,
            success(res){
              commentsdata['favor']=Number(commentsdata.favor)+1
              islike=1
              that.setData({commentsdata,islike})
            }
          })
          
        }
      })
    }else{
      api.dofavor(worksid,res=>{
        if(res.data.issuccess==1){
          wx.showToast({
            title: '取消成功',
            icon:'none',
            duration:1000,
            success(res){
              commentsdata['favor']=Number(commentsdata.favor)-1
              islike=0
              that.setData({commentsdata,islike})
            }
          })
          
        }
      })
    }
  },
  writecomment() {
    that.setData({
      sendshow: !0
    })
  },
  modsend() {
    that.setData({
      sendshow: !1
    })
  },
  input(e) {
    let  { newcomment } =that.data
    that.setData({
      newcomment: e.detail.value
    })
    console.log(newcomment,'newcommentnewcommentnewcomment')
  },
  // getcommlist(){
  //   let {  worksid} = that.data,commentlist=[]
  //   api.getWorkscomment(worksid,res=>{
  //     if(res.data.issuccess==1){
  //       commentlist=res.data.list
  //       that.setData({commentlist})
  //     }
  //   })
  // },
  addcomment() {
    let { newcomment, worksid} = that.data;
    if(newcomment==''){
      wx.showToast({
        title: '请输入评论',
        icon:'none'
      })
    }else{
      api.aoeWorkscomment({contents:newcomment,id:worksid},res=>{
        if(res.data.issuccess==1){
          wx.showToast({
            title: '评论成功',
            success(res){
              that.setData({newcomment:'',sendshow:!1})
            //  that.getcommlist()
            }
          })
        }else{
          wx.showToast({
            title: '评论失败',
            icon:'none'
          })
        }
      })
    }
  },
  addcomment() {
    let {
      newcomment,
      flag,
      data,
      worksid
    } = that.data;
    //判断用户是否授权
    let userinfo = wx.getStorageSync("userinfo");
    if (!userinfo && flag) {
      that.setData({
        flag: 0
      })
      wx.navigateTo({
        url: '../empower/empower',
      })
      return
    }
    if (!!userinfo) {
      //获取用户信息
      wx.getUserInfo({
        success: res => {
          // console.log(res, '12334131s')
          let {
            nickName,
            avatarUrl
          } = res.userInfo;
          let date = new Date();
          date = util.formatTime(date);
          //添加评论
          api.addcomment({
            username: nickName,
            avatarUrl,
            contents: newcomment,
            cid:worksid
          }, res => {
            console.log(res, 'aabcc')
            if (res.data.issuccess == 1) {
              that.setData({ newcomment: '' ,sendshow: !1},()=>{
               that.getdata(worksid) //刷新列表
              })
            } else if (res.data.msg = "wrong 包含敏感内容") {
              wx.showToast({
                title: '您输入的评论包含敏感内容，请重新输入',
                icon: 'none'
              })
            }
          })
        }
      })
    } else {
      api.addcomment({
        username: '匿名用户',
        avatarUrl: '',
        contents: newcomment,
        cid: worksid
      }, res => {
        console.log(res, 'aabcc')
        if (res.data.issuccess == 1) {
          that.setData({ newcomment: '' ,sendshow: !0}, () => {
            that.getdata(worksid) //刷新列表
          })
        } else if (res.data.msg = "wrong 包含敏感内容") {
          wx.showToast({
            title: '您输入的评论包含敏感内容，请重新输入',
            icon: 'none'
          })
        }
      })
    }  
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
      return{
        path:'pages/sampleReelsDetail/sampleReelsDetail?id='+that.data.id
      }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
    that.setData({duration:0,formatDuration:'00:00'})
    // innerAudioContext.offCanplay()
    innerAudioContext.destroy()
    // innerAudioContext.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    that.setData({duration:0,formatDuration:'00:00'})
    // innerAudioContext.offCanplay()
   // innerAudioContext.destroy()
    // innerAudioContext.stop()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})